<?php

namespace plugin\agent\app\api\controller;

use app\common\controller\BaseApiController;
use Carbon\Carbon;
use plugin\agent\app\admin\logic\AgentUserLogic;
use plugin\agent\app\model\AgentOrder;
use support\utils\MarkUtil;
use support\utils\Time;
use think\db\Query;

class AgentController extends BaseApiController
{
    protected function init()
    {
        parent::init();
        $this->logic = new AgentUserLogic();
    }

    public function info()
    {
        $where = [
            'user_id' => request()->uid,
        ];
        $data = $this->logic->where($where)->with([
            'user' => function (Query $query) {
                $query->field([
                    'id',
                    'nickname',
                    'avatar',
                ]);
            }
        ])->find();
        if ($data) {
            $data['current_month_order_count'] = AgentOrder::where([
                ['one_agent_id|two_agent_id|three_agent_id', '=', $data['agent_id']],
                ['create_time', 'between', [
                    Time::getMonthStartDateTime(time()),
                    Time::getMonthEndDateTime(time()),
                ]],
                ['status', '<>', 3]
            ])->count('*');
        }
        return $this->success($data);
    }

    public function checkIsAgent()
    {
        $where = [
            'user_id' => request()->uid,
        ];
        $data = $this->logic->where($where)->count();
        return $this->success([
            'is_agent' => $data > 0
        ]);
    }

    /**
     * 获取我的下级成员
     */
    public function getMyTeam()
    {
        $data = $this->logic->where([
            'user_id' => request()->uid,
        ])->field([
            'agent_id'
        ])->find();

        $where = [
            'parent_agent_id' => $data['agent_id'],
        ];
        $query = $this->logic
            ->where($where)
            ->with([
                'user' => function (Query $query) {
                    $query->field([
                        'id',
                        'nickname',
                        'mobile',
                        'avatar',
                    ]);
                }
            ]);
        $query->order("create_time desc");
        $data = $this->logic->getPageList($query);
        $data['records'] = array_map(function ($v) {
            $v['user']['mobile'] = MarkUtil::mobile($v['user']['mobile']);
            $v['create_time'] = Carbon::parse($v['create_time'])->format("Y年m月d日");
            return $v;
        }, $data['records']);
        return $this->success($data);
    }
}
